<template>
    <div id='wrap'>
        <h1>Proxy</h1>
    </div>
</template>
<script lang='ts'>
export default {
    name: 'Proxy',
}
</script>
<script lang='ts' setup>
import { ref } from 'vue';
import { h } from 'vue';
//日志记录：在访问对象属性时打印日志
interface A {
    name: string,
    age: string
}
const obj: A = { name: 'Alice', age: '16' }
const p = new Proxy(obj, {
    get(target, property: keyof A, receiver) {
        console.log(`属性${property}被访问了`);
        return obj[property];
    }
})

//数据校验：在设置对象时进行校验
//场景1
interface A {
    name: string,
    age: string
}
const obj1: A = { name: 'kano', age: '17' }

console.log(obj1);
const p1 = new Proxy(obj1, {
    set(target, property: keyof A, value, receiver) {
        if (property === 'name' && typeof value !== 'string' || property === 'age' && typeof value !== 'number') {
            throw new Error('类型错误');
        }
        target[property] = value;
        return target[property];
    }
})
console.log(p1.name = '123')
//场景2
interface B {
    name: string,
    age: number
}
const obj2: B = { name: 'hiyori', age: 16 }
const p2 = new Proxy(obj2, {
    set(target, property: keyof B, value, receiver) {
        console.log(`不给你修改属性${value}`)
        target[property] = 666;
        return target[property] = 666;
    },
    get(target, property: keyof B, receiver) {
        console.log(`属性${property}被访问了`)
        return target[property];
    }
})
p2.age = 14
console.log(p2.age);

//动态计算属性：动态生成属性值，而不修改原对象
const obj3 = { name: 'tenri' };
const p3 = new Proxy(obj3, {
    get(target, property) {
        if (property === 'age') {
            return `${target.name}的年龄是16`;
        }
        return target[property];
    },
})
console.log(p3.age);
console.log(obj3.age);

//
</script>
<style lang='scss'>
@use '@/assets/common.scss';
</style>